<template>
    <div>
      <!-- 弹窗提示 -->
      <el-dialog v-model="dialog.isdialog" title="填写详细信息" width="500px">
        <!-- 简介输入框 -->
        <el-form-item label="简介" :error="errors.summary">
          <el-input type="textarea" v-model="post.summary" placeholder="填写文章简介"></el-input>
        </el-form-item>
  
        <!-- 标签选择 -->
        <el-form-item label="选择标签" required :error="errors.categoryID">
          <div class="types-container">
            <el-tag
              v-for="type in availableTypes"
              :key="type.id"
              :closable="false"
              :class="{ 'selected-type': post.categoryID === type.id }"
              @click="selectTypeInDialog(type.id)"
              class="type-btn"
            >
              {{ type.name }}
            </el-tag>
          </div>
        </el-form-item>
  
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.isdialog = false">取 消</el-button>
          <el-button type="primary" @click="submitDialog">确 定</el-button>
        </div>
      </el-dialog>
  
      <!-- 编辑器区域 -->
      <el-container>
        <el-header>编辑</el-header>
        <el-main>
          <el-form :model="post" ref="postForm" enctype="multipart/form-data">
            <!-- 标题输入框 -->
            <el-form-item label="标题" prop="title" :error="errors.title">
              <el-input v-model="post.title"></el-input>
            </el-form-item>
  
            <!-- 图片上传 -->
            <el-upload action="/file/upload/file" :on-success="handleUploadSuccess" :before-upload="beforeImageUpload"
              :auto-upload="true" class="upload-demo">
              <el-button slot="trigger">插图上传</el-button>
              <template #tip>仅支持jpg/png格式，大小不超过2MB。</template>
            </el-upload>
            <div v-if="post.coverImageUrl" class="image-preview">
              <img :src="post.coverImageUrl" alt="预览图片" />
              <el-button type="danger" @click="removeUploadedImage">删除图片</el-button>
            </div>
  
            <!-- 内容输入框 -->
            <div class="article-content">
              <el-form-item label="内容" prop="content" class="editer-style" :error="errors.content">
                <el-input type="textarea" :rows="20" resize="both" v-model="post.content" class="edit-content"
                  @input="updateMarkdownPreview"></el-input>
              </el-form-item>
  
              <!-- Markdown预览区域 -->
              <el-container class="editer-style">
                <p style="margin: 0 0 0 1rem;">Markdown效果</p>
                <div id="markdownPreview" class="edit-content" v-html="convertToHtml(post.content)"></div>
              </el-container>
            </div>
  
            <!-- 提交按钮 -->
            <el-button type="primary" style="margin-left: 1rem;" @click="openDialog">提交</el-button>
          </el-form>
        </el-main>
      </el-container>
    </div>
  </template>
  
  <script setup lang="ts">
  import MarkdownIt from 'markdown-it';
  import { ElMessage } from 'element-plus';
  import { ref } from 'vue';
  import { useUserStore } from '@/stores/user';
  import axios from 'axios';
  import { useRoute } from 'vue-router';
  import router from '@/router';
  
  const route = useRoute();
  const md = new MarkdownIt();
  
  const availableTypes = ref([
    { id: 2, name: '后端' },  
    { id: 3, name: '前端' },
    { id: 4, name: '组件' },
    { id: 5, name: '开发工具' },
    { id: 6, name: '阅读' },
    { id: 7, name: '其他' }
  ]);
  
  // 选择的类型
  const selectTypeInDialog = (typeId: number) => {
    post.value.categoryID = typeId;
  };
  
  // 弹窗控制对象
  const dialog = ref({
    isdialog: false
  });
  
  // 表单数据和验证错误对象
  const post = ref({
    title: '',
    content: '',
    coverImageUrl: '',
    categoryID: 1,
    summary: '' // 新增简介字段
  });
  
  const errors = ref({
    title: '',
    content: '',
    categoryID: '',
    summary: ''
  });
  
  // 获取登录用户ID
  const user = useUserStore();
  const my_id = user.loginstatus ? user.userInfo.id : -1;
  const my_name = user.loginstatus ? user.userInfo.username : '游客';
  
  // 处理图片上传成功
  const handleUploadSuccess = (response: any) => {
    if (response && response.path) {
      post.value.coverImageUrl = response.path;
    } else {
      ElMessage.error('图片上传成功，但未返回预期的URL');
    }
  };
  
  // 删除上传的图片
  const removeUploadedImage = () => {
    post.value.coverImageUrl = '';
  };
  
  // Markdown内容转HTML
  const convertToHtml = (content: string) => {
    return md.render(content);
  };
  
  // 打开填写详细信息的弹窗
  const openDialog = () => {
    // 首先验证基础表单
    clearErrors();
    if (!validateForm()) return;
    dialog.value.isdialog = true;
  };
  
  // 确认弹窗中的内容并提交
  const submitDialog = () => {
    if (!post.value.summary || !post.value.categoryID) {
      errors.value.summary = !post.value.summary ? '简介不能为空' : '';
      errors.value.categoryID = !post.value.categoryID ? '请选择标签' : '';
      return;
    }
  
    // 准备提交表单
    const formData = {
      title: post.value.title,
      content: post.value.content,
      summary: post.value.summary,
      cover: post.value.coverImageUrl,
      authorID: my_id,
      authorName: my_name,
      categoryID: post.value.categoryID
    };
  console.log("kkkk",formData);
  
    axios.post('/api/articles', formData)
      .then(res => {
        dialog.value.isdialog = false;
        ElMessage.success('提交成功');
        router.push("/article/" + res.data.data.id);
      })
      .catch(() => {
        ElMessage.error('提交失败，请稍后再试');
      });
  };
  
  // 验证基础表单
  function validateForm() {
    let isValid = true;
  
    if (!post.value.title) {
      errors.value.title = '标题不能为空';
      isValid = false;
    }
  
    if (!post.value.content) {
      errors.value.content = '内容不能为空';
      isValid = false;
    }
  
    return isValid;
  }
  
  // 清除错误
  function clearErrors() {
    errors.value.title = '';
    errors.value.content = '';
    errors.value.categoryID = '';
    errors.value.summary = '';
  }
  </script>
  
  <style scoped>
  /* 头像上传区域样式 */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    width: 100px;
    height: 100px;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  /* 文本区域样式 */
  .resizable-textarea {
    resize: both;
    overflow: auto;
    min-width: 300px;
    min-height: 100px;
  }
  
  .article-content {
    display: flex;
    overflow: hidden;
  }
  
  .editer-style {
    display: inline-block;
    width: 42vw;
  }
  
  .edit-content {
    overflow: auto;
    height: 60vh;
  }
  
  .edit-content:last-child {
    margin-left: 1rem;
  }
  
  .form-group {
    margin-bottom: 15px;
  }
  
  .types-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .type-btn {
    cursor: pointer;
  }
  
  .selected-type {
    background-color: #409eff !important;
    color: white !important;
  }
  
  .type-limit-tip {
    font-size: 12px;
    color: #aaa;
    margin-top: 5px;
  }
  </style>
  
  
  
  <style scoped>
  /* 头像上传区域样式 */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    width: 100px;
    height: 100px;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  /* 文本区域样式 */
  .resizable-textarea {
    resize: both;
    overflow: auto;
    min-width: 300px;
    min-height: 100px;
  }
  
  .article-content {
    display: flex;
    overflow: hidden;
  }
  
  .editer-style {
    display: inline-block;
    width: 42vw;
  }
  
  .edit-content {
    overflow: auto;
    height: 60vh;
  }
  
  .edit-content:last-child {
    margin-left: 1rem;
  }
  
  .form-group {
    margin-bottom: 15px;
  }
  
  .types-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .type-btn {
    cursor: pointer;
  }
  
  .selected-type {
    background-color: #409eff !important;
    color: white !important;
  }
  
  .type-limit-tip {
    font-size: 12px;
    color: #aaa;
    margin-top: 5px;
  }
  </style>
  